<template>
  <a-layout class="chat-layout">
    <a-page-header class="chat-header" :title="`🐢 AI 海龟汤 - 房间 ${roomId}`" />
    <a-layout-content class="chat-content">
      <div class="message-list" ref="messageListRef">
        <div v-for="(msg, index) in messages" :key="index" :class="['message-item', msg.sender]">
          <a-avatar class="avatar">
            {{ msg.sender === 'user' ? '我' : '🤖' }}
          </a-avatar>
          <div class="message-bubble">
            <a-spin :spinning="msg.loading">
              <p v-if="!msg.loading">{{ msg.text }}</p>
              <p v-else>思考中...</p>
            </a-spin>
          </div>
        </div>
      </div>
    </a-layout-content>
    <a-layout-footer class="chat-footer">
      <div class="action-buttons">
        <a-button type="primary" @click="handleStart" :disabled="isGameStarted || isLoading" ghost>🚀 开始</a-button>
        <a-button type="danger" @click="handleEnd" :disabled="!isGameStarted || isGameEnded || isLoading" ghost>🛑 结束</a-button>
        <a-button @click="handleRestart">🔄 重新开始</a-button>
      </div>
      <a-input-group compact class="input-area">
        <a-input
          v-model:value="newMessage"
          placeholder="输入你的猜测或提问..."
          @pressEnter="handleSend"
          :disabled="!isGameStarted || isGameEnded || isLoading"
          style="flex-grow: 1;"
        />
        <a-button type="primary" @click="handleSend" :loading="isLoading" :disabled="!isGameStarted || isGameEnded || !newMessage.trim()">发送</a-button>
      </a-input-group>
    </a-layout-footer>
  </a-layout>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import axios from 'axios';
import { message as antMessage } from 'ant-design-vue';
import { doChatUsingPost } from '@/api/chatController.js' // Import message component for notifications

// --- State ---
const roomId = ref(null);
const messages = ref([]); // { sender: 'ai' | 'user', text: string, loading?: boolean }
const newMessage = ref('');
const isGameStarted = ref(false);
const isGameEnded = ref(false);
const isLoading = ref(false); // Loading state for sending messages
const messageListRef = ref(null); // Ref for scrolling

// --- Lifecycle Hooks ---
onMounted(() => {
  // Generate a random room ID when component mounts
  roomId.value = Math.floor(1000 + Math.random() * 9000);
  // Optional: Fetch initial room list if needed, but not part of the chat interaction logic
  // fetchRoomList();
});

// --- Methods ---
/* // Optional: Function to fetch room list - uncomment if needed
async function fetchRoomList() {
  try {
    const response = await axios.get('http://localhost:8080/api/chat/rooms');
    console.log('Available rooms:', response.data);
    // You might want to do something with the room list here
  } catch (error) {
    console.error('Error fetching room list:', error);
    antMessage.error('获取房间列表失败');
  }
}
*/

async function scrollToBottom() {
  await nextTick(); // Wait for the DOM to update
  const container = messageListRef.value;
  if (container) {
    container.scrollTop = container.scrollHeight;
  }
}

async function sendMessage(textToSend) {
  if (!textToSend || isLoading.value) return;

  isLoading.value = true;

  // Add user message immediately
  messages.value.push({ sender: 'user', text: textToSend,loading: false});
  scrollToBottom(); // Scroll after adding user message

  // Add a temporary loading message for AI
  const aiLoadingMsgIndex = messages.value.length;
  messages.value.push({ sender: 'ai', text: '', loading: false });
  scrollToBottom(); // Scroll after adding AI loading placeholder


  const currentUserMessage = textToSend; // Store the message being sent
  if (currentUserMessage.trim() === '开始') {
    isGameStarted.value = true;
  }
  newMessage.value = ''; // Clear input field immediately after adding user message

  try {
    const response=await doChatUsingPost({
      roomId: roomId.value,
       message: currentUserMessage
    });
    // const response = await axios.post(`http://localhost:8080/api/chat/${roomId.value}/send`, null, {
    //   params: { message: currentUserMessage }
    // });

    // Update the loading message with the actual AI response
    messages.value[aiLoadingMsgIndex] = { sender: 'ai', text: response.data, loading: false };

    // Check if the game has ended
    if (response.data.includes('【游戏已结束】')) {
      isGameEnded.value = true;
      antMessage.success('🎉 游戏结束！');
    }

    // Ensure game started state is true if AI responded positively to "开始"
    if (currentUserMessage.trim() === '开始' && !isGameEnded.value) {
      isGameStarted.value = true;
    }

  } catch (error) {
    console.error('Error sending message:', error);
    antMessage.error('发送消息失败，请稍后再试');
    // Remove the loading message on error
    messages.value.splice(aiLoadingMsgIndex, 1);
  } finally {
    isLoading.value = false;
    scrollToBottom(); // Scroll after receiving AI message or error
  }
}

function handleStart() {
  if (!isGameStarted.value) {
    sendMessage('开始');
  }
}

function handleEnd() {
  // Although the button is disabled when game ends via AI message,
  // provide a way to end manually if needed (optional).
  if (isGameStarted.value && !isGameEnded.value) {
    sendMessage('结束'); // Send "结束" to backend if required by logic
    // Or just update frontend state:
    // isGameEnded.value = true;
    // antMessage.info('游戏手动结束。');
  }
}

function handleSend() {
  const text = newMessage.value.trim();
  if (text && isGameStarted.value && !isGameEnded.value) {
    sendMessage(text);
  } else if (text === '开始' && !isGameStarted.value) {
    handleStart(); // Allow starting via input field
  }
}

function handleRestart() {
  window.location.reload();
}

</script>

<style scoped>
.chat-layout {
  height: 100vh; /* Full viewport height */
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5; /* Light background */
}

.chat-header {
  background-color: #fff;
  border-bottom: 1px solid #e8e8e8;
  padding: 10px 24px; /* Adjust padding */
  z-index: 10; /* Keep header on top */
  text-align: center; /* Center title */
}

.chat-content {

  flex-grow: 1; /* Take remaining space */
  overflow-y: auto; /* Allow scrolling for messages */
  padding: 16px 24px;
  display: flex;
  flex-direction: column;
}

.message-list {
  flex-grow: 1;
  overflow-y: auto; /* Scroll within the list itself */
  padding-right: 10px; /* Space for scrollbar */
}

/* Scrollbar styling (optional) */
.message-list::-webkit-scrollbar {
  width: 6px;
}
.message-list::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}
.message-list::-webkit-scrollbar-track {
  background-color: rgba(0, 0, 0, 0.1);
}


.message-item {
  display: flex;
  margin-bottom: 16px;
  align-items: flex-end; /* Align avatar and bubble nicely */
}

.message-item.user {
  flex-direction: row-reverse; /* My messages on the right */
}

.avatar {
  flex-shrink: 0;
  margin: 0 8px;
}

.message-item.user .avatar {
  background-color: #1890ff; /* User avatar color */
}

.message-item.ai .avatar {
  background-color: #52c41a; /* AI avatar color */
}

.message-bubble {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 15px;
  word-wrap: break-word; /* Break long words */
  position: relative; /* For potential future additions like timestamps */
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.message-item.user .message-bubble {
  background-color: #e6f7ff; /* Light blue for user messages */
  border-bottom-right-radius: 5px; /* Pointy corner */
  color: #333;
}

.message-item.ai .message-bubble {
  background-color: #f6ffed; /* Light green for AI messages */
  border-bottom-left-radius: 5px; /* Pointy corner */
  color: #333;
}

.message-bubble p {
  margin: 0;
  line-height: 1.5;
}

.chat-footer {
  padding: 10px 24px;
  background-color: #fff;
  border-top: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column; /* Stack buttons and input */
  gap: 10px; /* Space between buttons and input area */
}

.action-buttons {
  display: flex;
  justify-content: center; /* Center buttons */
  gap: 15px; /* Space between buttons */
}

.input-area {
  display: flex;
  align-items: center;
}

.input-area .ant-input {
  border-right: none; /* Nicer look with the button */
  border-top-left-radius: 6px; /* Consistent rounding */
  border-bottom-left-radius: 6px;
}

.input-area .ant-btn {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}
</style>
'''})
